import { AssetManager, AudioClip, Material } from "cc";
import { PREVIEW } from "cc/env";
import Core from "db://app/Core";
import AudioEngine from "db://app/manager/sound/AudioEngine";
import { i18n, IAssetBundle, IDevice } from "db://fairygui-xforge/UIDevice";

export class FGUIDeviceImpl implements IDevice {
    public i18n: i18n = null;
    public graphicsMaterial: Material;

    public playOneShotSound (clip: AudioClip, volumeScale?: number): void {
        AudioEngine.inst.playEffect(clip, volumeScale, false);
    }

    playDefaultButtonSound(): void {
        const soundManager = Core.inst.manager.sound;
        if (!(<any>soundManager)["defaultEffectName"]) {
            return;
        }
        soundManager.playDefaultEffect();
    }

    playOneShotSoundWithName(name: string, volumeScale?: number): void {
        Core.inst.manager.sound.playEffect({
            name: name,
            volume: volumeScale,
        });
    }

    public loadBundle (bundleName: string): Promise<IAssetBundle> {
        return new Promise<IAssetBundle>((resolve, reject) => {
            Core.inst.manager.loader.loadBundle({
                bundle: bundleName,
                onComplete: (result: AssetManager.Bundle) => {
                    if (result) {
                        const ab = Core.inst.manager.loader.getAssetsBundle(bundleName);
                        if (PREVIEW) {
                            ab.addRef();
                        }
                        resolve(ab);
                    } else {
                        reject("no bundle loaded");
                    }
                }
            });
        });
    }
}